package com.ukefu.webim.web.handler.api.rest;

import static org.elasticsearch.index.query.QueryBuilders.termQuery;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang3.StringUtils;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageImpl;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import com.ukefu.core.UKDataContext;
import com.ukefu.util.Menu;
import com.ukefu.util.es.SearchTools;
import com.ukefu.util.es.UKDataBean;
import com.ukefu.webim.service.repository.MetadataRepository;
import com.ukefu.webim.util.RestResult;
import com.ukefu.webim.util.RestResultType;
import com.ukefu.webim.web.handler.Handler;
import com.ukefu.webim.web.model.MetadataTable;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;

@RestController
@RequestMapping("/api/salename")
@Api(value = "名单列表" , description = "按当前坐席查询其下所有名单")
public class ApiSaleNameController extends Handler{
	

	@Autowired
	private MetadataRepository metadataRes;
	
	/**
	 * @param request
	 * @param username	搜索用户名，精确搜索
	 * @return
	 */
	@RequestMapping( method = RequestMethod.GET)
	@Menu(type = "apps" , subtype = "organ" , access = true)
	@ApiOperation("返回按当前坐席查询其下所有名单")
    public ResponseEntity<RestResult> list(HttpServletRequest request ,ModelMap map,String owneruser) {
		BoolQueryBuilder queryBuilder = new BoolQueryBuilder();
		queryBuilder.must(termQuery("status", UKDataContext.NamesDisStatusType.DISAGENT.toString()));
		queryBuilder.must(termQuery(UKDataContext.UKEFU_SYSTEM_DIS_AGENT, super.getUser(request).getId()));
		PageImpl<UKDataBean> dataList = SearchTools.search(super.search(queryBuilder, map, request), super.getP(request),
				super.getPs(request));
        return new ResponseEntity<>(new RestResult(RestResultType.OK, dataList), HttpStatus.OK);
    }
	
	@RequestMapping(value = "/detail")
	@Menu(type = "apps" , subtype = "organ" , access = true)
	@ApiOperation("返回按当前坐席查询其下所有名单")
    public ResponseEntity<RestResult> detail(HttpServletRequest request ,ModelMap map,String namesid ,String meta) {
		UKDataBean dataBean = null;
		if (!StringUtils.isBlank(namesid)) {
			MetadataTable table = metadataRes.findByTablenameIgnoreCase(meta);
			map.put("table", table);
			if (table != null) {
				dataBean = new UKDataBean();
				dataBean.setId(namesid);
				dataBean.setTable(table);

				dataBean = SearchTools.get(dataBean);
				map.put("dataBean", dataBean);
			}
		}
        return new ResponseEntity<>(new RestResult(RestResultType.OK, dataBean), HttpStatus.OK);
    }
	
}